package com.example.actordemo4.cluster;

import akka.actor.AbstractActor;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import akka.cluster.ClusterEvent.MemberEvent;
import akka.cluster.ClusterEvent.MemberRemoved;
import akka.cluster.ClusterEvent.MemberUp;
import akka.cluster.ClusterEvent.UnreachableMember;
import akka.cluster.Member;

public class ClusterActor extends AbstractActor {
    Cluster cluster = Cluster.get(getContext().system());

    @Override
    public void preStart() throws Exception {
        cluster.subscribe(getSelf(), ClusterEvent.initialStateAsEvents(),
                UnreachableMember.class, MemberEvent.class);

    }

    @Override
    public void postStop() throws Exception {
        cluster.unsubscribe(getSelf());
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(MemberUp.class,msg->{

                    MemberUp memberUp = msg;
                    Member member = memberUp.member();
                    System.out.println(getSelf()+"-->Member"+member+"is up:the role is"+ member.roles());
                }).match(UnreachableMember.class,msg->{
                    UnreachableMember un = msg ;
                    Member member = un.member();
                    System.out.println(getSelf()+"-->UnreachableMember"+member+
                            "is detected as inreachable :the role is"+ member.roles());
                }).match(MemberRemoved.class,msg->{
                    MemberRemoved removed = msg;
                    Member member = removed.member();
                    System.out.println(getSelf()+"-->removed"+member+
                            "removed :the role is"+ member.roles());
                }).match(MemberEvent.class,msg->{
                    MemberEvent event = msg;
                    Member member = event.member();
                    System.out.println(getSelf()+"-->event"+member+
                            "event :the role is"+ member.roles());
                }).matchAny(msg->{
                    System.out.println(getSelf()+"--->Other"+msg);
                }).build();
    }

    public static void main(String[] args) {
        ActorSystem actorSystem = ActorSystem.create("sys");
        actorSystem.actorOf(Props.create(ClusterActor.class),"clusterActor");
    }
}
